package com.cskaoyan.servlet;

import com.cskaoyan.bean.vo.AdParameter;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.PageData;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.model.MarketAd;
import com.cskaoyan.service.AdService;
import com.cskaoyan.service.impl.AdServiceImpl;
import com.cskaoyan.utils.JacksonUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/admin/ad/*")
public class AdminAdServlet extends CommonServlet {
    AdService adService=new AdServiceImpl();
    // 查询
    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        //获取参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        AdParameter parameter = new AdParameter();
        // 传入parameter
        BeanUtils.copyProperties(parameter,parameterMap);
        PageData data= adService.list(parameter);

        return BaseRespVo.ok(data);
    }

    public BaseRespVo create(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        // 参数变为对象
        String jsonStr = request.getReader().readLine();
        MarketAd marketAd = JacksonUtil.read(jsonStr, MarketAd.class);

        // 创建
        adService.create(marketAd);
        return BaseRespVo.ok(null);
    }

    public BaseRespVo update(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");

        String jsonStr = request.getReader().readLine();
        MarketAd marketAd = JacksonUtil.read(jsonStr, MarketAd.class);

        adService.update(marketAd);

        return BaseRespVo.ok(null);
    }

    public BaseRespVo delete(HttpServletRequest request,HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");

        String jsonStr = request.getReader().readLine();
        MarketAd marketAd = JacksonUtil.read(jsonStr, MarketAd.class);

        adService.delete(marketAd);

        return BaseRespVo.ok(null);
    }
}
